#-*-coning:utf-8-*-
import numpy as np
from pymouse import PyMouse
import time
import json
import os
from PIL import Image


def screenshot():
    """截图"""
    command = 'import -window root -crop {0}x{1}+{2}+{3} screenshot.png'
    command = command.format(350,300,100,400)
    os.system(command)
    scr = Image.open('screenshot.png')
    scr = scr.convert('L')
    return scr

def erzhihua(img):
    """二值化"""
    table = []

    for i in range(256):
        if i > 200:         #二值化灰度阈值
            table.append(0)
        else:
            table.append(1)
    img = img.point(table,'1')
    return img

def h_cut(scr):
    """横向分割"""
    width, _= scr.size
    px = list(np.sum(np.array(scr)==0,axis=1))
#    for i in px:
#        print(i)
    y0 = []
    for y in range(len(px)):
        if px[y] > 1:
            y0.append(y)
    #边界
    cut_list = [y0[0]]
    for i in range(1,len(y0)):
        if abs(y0[i] - y0[i-1]) > 1:
            cut_list.extend([y0[i-1],y0[i]])
    cut_list.append(y0[-1])

    if len(cut_list) == 4:
        cut_img1 = scr.crop([0, cut_list[0], width, cut_list[1]])
        cut_img2 = scr.crop([0, cut_list[2], width, cut_list[3]])
        return [cut_img1,cut_img2]
    else:
        print(cut_list)
        print('Horizontal cut failed.')
        return

def v_cut(img):
    """纵向切割"""
    _, height= img.size
    px = list(np.sum(np.array(img) == 0, axis=0))
    x0 = []
    for x in range(len(px)):
        if px[x] >1:
            x0.append(x)

    cut_list = [x0[0]]
    for i in range(1,len(x0)):
        if abs(x0[i] - x0[i - 1])> 1:
            cut_list.extend([x0[i-1],x0[i]])
    cut_list.append(x0[-1])

    cut_imgs=[]
    if len(cut_list) % 2 == 0:
        for i in range(len(cut_list) // 2):
            cut_img = img.crop([cut_list[i * 2], 0, cut_list[i * 2 + 1], height])
            cut_imgs.append(cut_img)
        return cut_imgs
    else:
        print(cut_list)
        print('Vertical cut failed.')
        return

def hashing(img):
    """计算哈希值"""
    img = img.resize((20, 30), Image.LANCZOS).convert("L")
    px = np.array(img).flatten()
    hash_val = (px > px.mean()).astype(int)
    hash_val = ''.join(str(e) for e in hash_val)
    return hash_val

def hamming(hash1, hash2):
    """计算汉明距离"""
    if len(hash1) != len(hash2):
#           print('hash1: ', hash1)
#           print('hash2: ', hash2)
        raise ValueError("Undefined for sequences of unequal length")

    return sum(i != j for i, j in zip(hash1, hash2))

def recognize(chars1,chars2):
    with open('HashFiles/hash.json','r') as fp:
        hash_vals = json.load(fp)

    nearness = {}   #最近距离
    expr = ''       #表达式
    chars1.extend(chars2)
    for char in chars1:
        hash_val = hashing(char)
        for h in hash_vals:
            nearness[h] = hamming(hash_val, hash_vals[h])
        expr += sorted(nearness.items(),key = lambda d: d[1])[0][0] #排序，取第一个
        #        print (expr)

    expr = expr.replace('subtract','-').replace('plus', '+').replace('equal', '==')
    return expr

def play():
    m = PyMouse()
    flag = ""
    i=True
    while i:
#        i -= 1
        time.sleep(0.1)
        img=screenshot()
        img = erzhihua(img)
        h_cut_imgs = h_cut(img)
        chars1 = v_cut(h_cut_imgs[0])
        chars2 = v_cut(h_cut_imgs[1])
        expr = recognize(chars1,chars2)
        print(expr)
        if flag == expr:
            continue
        else:
            flag = expr
            try:
                if eval(expr):
                    m.click(150,850,1)
                else:
                    m.click(350,850,1)

            except:
                print("lose")
                break
#                try:
#                    break

                #    expr = expr.replace('==','44',1)
                 #   print(expr)
                  #  if eval(expr):
                  #      m.click(350,850,1)
                  #  else:
                  #      m.click(150,850,1)'''
#                except:
 #                   expr = expr.replace('44','==')
 #                   expr[-2,]='44'
 #                   if eval(expr):
 #                       m.click(150,850,1)
  #                  else:
   #                     m.click(350,850,1)

if __name__ == '__main__':
    play()
